/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package org.springframework.mock.web;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;

public class MockRequestDispatcher implements RequestDispatcher {
	private final Log logger = LogFactory.getLog(super.getClass());
	private final String resource;

	public MockRequestDispatcher(String resource) {
		Assert.notNull(resource, "resource must not be null");
		this.resource = resource;
	}

	/**
	 * 请求转发
	 * @param request
	 * @param response
	 */
	public void forward(ServletRequest request, ServletResponse response) {
		Assert.notNull(request, "Request must not be null");
		Assert.notNull(response, "Response must not be null");
		if (response.isCommitted()) {
			throw new IllegalStateException("Cannot perform forward - response is already committed");
		}
		getMockHttpServletResponse(response).setForwardedUrl(this.resource);
		if (this.logger.isDebugEnabled())
			this.logger.debug("MockRequestDispatcher: forwarding to [" + this.resource + "]");
	}

	/**
	 * jsp中的include
	 *
	 * @param request
	 * @param response
	 */
	public void include(ServletRequest request, ServletResponse response) {
		Assert.notNull(request, "Request must not be null");
		Assert.notNull(response, "Response must not be null");
		getMockHttpServletResponse(response).addIncludedUrl(this.resource);
		if (this.logger.isDebugEnabled())
			this.logger.debug("MockRequestDispatcher: including [" + this.resource + "]");
	}

	protected MockHttpServletResponse getMockHttpServletResponse(ServletResponse response) {
		if (response instanceof MockHttpServletResponse) {
			return ((MockHttpServletResponse) response);
		}
		if (response instanceof HttpServletResponseWrapper) {
			return getMockHttpServletResponse(((HttpServletResponseWrapper) response).getResponse());
		}
		throw new IllegalArgumentException("MockRequestDispatcher requires MockHttpServletResponse");
	}
}